package com.zhongxi.guoyuan.OffLineShop;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RatingBar;
import android.widget.TextView;

import com.baidu.navisdk.adapter.BNRoutePlanNode;
import com.baidu.navisdk.adapter.BaiduNaviManager;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.loader.ImageLoader;
import com.zhongxi.guoyuan.OffLineShop.Adapter.EvaluateAdapter;
import com.zhongxi.guoyuan.OffLineShop.ConnectNet.NetWork;
import com.zhongxi.guoyuan.OffLineShop.Model.StoreDetail;
import com.zhongxi.guoyuan.OffLineShop.Model.StoreMessage;
import com.zhongxi.guoyuan.OffLineShop.UI.OffLineShopDetailActivtiy;
import com.zhongxi.guoyuan.OffLineShop.UI.PayMoneyActivity;
import com.zhongxi.guoyuan.OffLineShop.UrlOffLine.RelativeUrl;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.entity.comment.CommentData;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.CommonTool;
import com.zhongxi.guoyuan.utils.Constants;
import com.zhongxi.guoyuan.utils.DataUtil;
import com.zhongxi.guoyuan.utils.ImageUtils;
import com.zhongxi.guoyuan.utils.ToastUtil;
import com.zhongxi.guoyuan.utils.UiUtils;
import com.zhongxi.guoyuan.view.MapNaviActivity;
import com.zhongxi.guoyuan.view.user.LoginActivity;
import com.zhongxi.guoyuan.widget.view.MyScrollView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

/**
 * Created by Administrator on 2018/1/12.
 */

public class DetailStoreFragment extends OffLineBaseFragment implements MyScrollView.OnScrollListener {

    @Bind(R.id.banner)
    Banner mBanner;
    @Bind(R.id.flow)
    FrameLayout mFlow;
    @Bind(R.id.tv_storeName)
    TextView mTvStoreName;
    @Bind(R.id.tv_address)
    TextView mTvAddress;
    @Bind(R.id.tv_distance)
    TextView mTvDistance;
    @Bind(R.id.openingHours)
    TextView mOpeningHours;
    @Bind(R.id.tv_type)
    TextView mTvType;
    @Bind(R.id.tv_hot)
    TextView mTvHot;
    @Bind(R.id.iv_call)
    ImageView mIvCall;
    @Bind(R.id.rb_offline)
    RatingBar mRbOffline;
    @Bind(R.id.tv_introduction)
    TextView mTvIntroduction;
    @Bind(R.id.linearLayout)
    LinearLayout mLinearLayout;
    @Bind(R.id.recycleView)
    RecyclerView mRecycleView;
    @Bind(R.id.myScrollView)
    MyScrollView mMyScrollView;
    @Bind(R.id.ll_share)
    LinearLayout mLlShare;
    @Bind(R.id.ll_gothere)
    LinearLayout mLlGothere;
    @Bind(R.id.ll_check_out)
    LinearLayout mLlCheckOut;
    @Bind(R.id.linearBottom)
    LinearLayout mLinearBottom;
    @Bind(R.id.tv_douType)
    TextView mTvDouType;
    @Bind(R.id.emptyView)
    FrameLayout emptyView;

    @Bind(R.id.textView)
    TextView mTextView;

    @Bind(R.id.linearBegin)
    LinearLayout lineargegin;
    @Bind(R.id.linearStop)
    LinearLayout linearstop;
    @Bind(R.id.linearScrollBody)
    LinearLayout lienarScrollbody;
    @Bind(R.id.tv_shopinfo)
    TextView tvShopinfo;
    @Bind(R.id.tv_clientEvaluation)
    TextView tvClientEvaluation;

    private StoreDetail mStoreDetail;
    private int mMeasuredHeight;
    private EvaluateAdapter mAdapter;
    private List<CommentData> mCommentDataList = new ArrayList<>();
    private PopupWindow popupWindow;
    private SHARE_MEDIA platform;
    private boolean mIsMoreLoad;
    private ProgressDialog dialog;

    private final static String authComArr[] = {Manifest.permission.READ_PHONE_STATE};
    private int authComRequestCode = 2;
    private boolean hasRequestComAuth = false;

    private DialogInterface.OnKeyListener keyListener = new DialogInterface.OnKeyListener() {
        @Override
        public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
            if (i == KeyEvent.KEYCODE_BACK && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
            return false;
        }
    };
    private boolean mIsMeasure;

    @Override
    protected void initParams() {
        super.initParams();
        if (getArguments() != null) {
            mStoreDetail = (StoreDetail) getArguments().getSerializable("storeDetail");
        }
    }

    @Override
    protected View init() {
        View mView = UiUtils.inflate(R.layout.fragment_detail_store);
        ButterKnife.bind(this, mView);
        return mView;
    }

    @Override
    protected void initView(View view) {
        super.initView(view);
        mTextView.setText("暂无评论显示,敬请期待!");
        ImageUtils.setHeight(getActivity(), Constants.flowRate, mFlow);
        mLinearLayout.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                if (!mIsMeasure) {
                    mMeasuredHeight = mLinearLayout.getMeasuredHeight() - tvShopinfo.getMeasuredHeight();
                    mIsMeasure = true;
                }
                return true;
            }
        });
        lunBo(mStoreDetail.getData().getImages());
        getDate();
        mRecycleView.setLayoutManager(new LinearLayoutManager(UiUtils.getContext()));
        mRecycleView.setNestedScrollingEnabled(false);
        if (mAdapter == null) {
            mAdapter = new EvaluateAdapter(mCommentDataList);
            mRecycleView.setAdapter(mAdapter);
        }
    }

    private void lunBo(ArrayList<String> images) {
        mBanner.isAutoPlay(true);
        mBanner.setDelayTime(3000);
        mBanner.setIndicatorGravity(BannerConfig.CENTER);
        List<String> mStringList = new ArrayList<>();
        for (int i = 0; i < images.size(); i++) {
            mStringList.add(Url.IMG_URL + images.get(i));
        }
        mBanner.setImages(mStringList).setImageLoader(new ImageLoader() {
            @Override
            public void displayImage(Context context, Object path, ImageView imageView) {
                Glide.with(UiUtils.getContext()).load(path).placeholder(R.mipmap.iv_loading).into(imageView);
            }
        }).start();
    }

    @Override
    public void onStart() {
        super.onStart();
        mBanner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        mBanner.stopAutoPlay();
    }

    private void getDate() {
        StoreMessage mData = mStoreDetail.getData();
        mTvStoreName.setText(mData.getName());
        mTvAddress.setText(mData.getAddress());
        String mDistance = CommonTool.getDistanceKM(Double.parseDouble(MyApplication.getInstance().getLongitude()),
                Double.parseDouble(MyApplication.getInstance().getLatitude()), mData.getLongitude(), mData.getLatitude());
        if (DataUtil.moreThanOther(mDistance, "1")) {
            mTvDistance.setText(mDistance + "km");
        } else {
            mTvDistance.setText(CommonTool.getDistanceOfM(Double.parseDouble(MyApplication.getInstance().getLongitude()),
                    Double.parseDouble(MyApplication.getInstance().getLatitude()), mData.getLongitude(), mData.getLatitude()) + "m");
        }
        mOpeningHours.setText(mData.getWorkertime());
        if ("100".equals(mData.getDiscount())) {
            mTvDouType.setText("无折扣");
        } else {
            mTvDouType.setText(mData.getDiscount() + " 折消费");
        }
        mTvType.setText(mData.getCatename());
        mTvHot.setText(getString(R.string.pageview, mData.getOrdernum()));
        String mStarlevel = mData.getStarlevel();
        if (!TextUtils.isEmpty(mStarlevel)) {
            mRbOffline.setRating(Float.parseFloat(mStarlevel));
        }
        mTvIntroduction.setText(mData.getSubject());
    }

    @Override
    protected void initNet() {
        super.initNet();
        unsubscribe();
        mDisposable = NetWork.getOffLineApiOfJson().getEvaluateApi(RelativeUrl.EvaulateInfo + MyApplication.getInstance().getUrl(),
                MyApplication.getInstance().getCheck(false), mStoreDetail.getData().getId(), page)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ResponseBody>() {
                    @Override
                    public void accept(ResponseBody responseBody) throws Exception {
                        JSONObject jsonObject = new JSONObject(responseBody.string());
                        JSONObject safeobj = jsonObject.optJSONObject("safeobj");
                        MyApplication.getInstance().sharedPrefrences.edit().putString("now", safeobj.optString("now")).commit();
                        MyApplication.getInstance().sharedPrefrences.edit().putString("sk", safeobj.optString("safestring")).commit();
                        int mCode = jsonObject.optInt("code");
                        int mTotalNum = jsonObject.optInt("totalNum");  //  评论数
                        JSONArray mComments = jsonObject.optJSONArray("comments");
                        JSONObject mUser = jsonObject.optJSONObject("user");
                        if (page == 1) {
                            mCommentDataList.clear();
                        }
                        if (mCode == 1) {
                            if (mComments != null && mComments.length() > 0) {
                                List<CommentData> mCommentData = new Gson().fromJson(mComments.toString(), new TypeToken<List<CommentData>>() {
                                }.getType());
                                mIsMoreLoad = true;
                                mCommentDataList.addAll(mCommentData);
                                mAdapter.setUserInfo(mUser);
                                mAdapter.notifyDataSetChanged();
                                mAdapter.setLoadingState(mAdapter.LOADCOMPLENT);
                            } else {
                                mIsMoreLoad = false;
                                if (page > 1) {
                                    mAdapter.setLoadingState(mAdapter.LOADEND);
                                    page--;
                                }
                            }
                        } else {
                            mIsMoreLoad = false;
                            ToastUtil.show(getString(R.string.loseData, mCode));
                            if (page > 1) {
                                page--;
                            }
                        }
                        if (mCommentDataList.size() > 0) {
                            emptyView.setVisibility(View.INVISIBLE);
                            mRecycleView.setVisibility(View.VISIBLE);
                        } else {
                            emptyView.setVisibility(View.VISIBLE);
                            mRecycleView.setVisibility(View.INVISIBLE);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        mIsMoreLoad = false;
                        ToastUtil.show(getString(R.string.load_error));
                    }
                });
    }

    @Override
    protected void initListener() {
        super.initListener();
        mMyScrollView.setOnScrollListener(this);
    }

    @OnClick({R.id.iv_call, R.id.ll_share, R.id.ll_gothere, R.id.ll_check_out})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_call:
                String mPhone = mStoreDetail.getData().getPhone();
                if (TextUtils.isEmpty(mPhone)) {
                    ToastUtil.show(getString(R.string.empty_phone));
                } else {
                    Intent mIntent = new Intent(Intent.ACTION_DIAL);
                    Uri mParse = Uri.parse("tel:" + mPhone);
                    mIntent.setData(mParse);
                    startActivity(mIntent);
                }
                break;
            case R.id.ll_share:
                //分享
                if (null != popupWindow && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                } else {
                    initPopuWindow();
                }
                break;
            case R.id.ll_gothere:
                if (mStoreDetail.getData().getLongitude() != null && mStoreDetail.getData().getLatitude() != null) {
                    if (dialog == null) {
                        dialog = new ProgressDialog(getActivity());
                    }
                    dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);  //样式为圆形
                    dialog.setCancelable(false);
                    dialog.setOnKeyListener(keyListener);
                    dialog.setMessage("正在获取数据,请稍后...");
                    dialog.show();
                    if (BaiduNaviManager.isNaviInited()) {
                        routeplanToNavi(BNRoutePlanNode.CoordinateType.BD09LL);
                    } else {
                        if (dialog != null && dialog.isShowing()) {
                            dialog.dismiss();
                        }
                    }
                } else {
                    ToastUtil.show(getString(R.string.loseDataOfBaiduNavi));
                }
                break;
            case R.id.ll_check_out:
                Intent mIntent = new Intent(UiUtils.getContext(), PayMoneyActivity.class);
                mIntent.putExtra("secret", mStoreDetail.getPaysecret());
                startActivity(mIntent);
                break;
        }
    }


    private boolean hasCompletePhoneAuth() {
        PackageManager pm = getActivity().getPackageManager();
        for (String auth : authComArr) {
            if (pm.checkPermission(auth, getActivity().getPackageName()) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }


    private void routeplanToNavi(BNRoutePlanNode.CoordinateType coType) {
        // 权限申请
        if (android.os.Build.VERSION.SDK_INT >= 23) {
            // 保证导航功能完备
            if (!hasCompletePhoneAuth()) {
                if (!hasRequestComAuth) {
                    hasRequestComAuth = true;
                    requestPermissions(authComArr, authComRequestCode);
                    return;
                }
            }

        }
        BNRoutePlanNode sNode = null;
        BNRoutePlanNode eNode = null;
        switch (coType) {
            case BD09LL: {
                sNode = new BNRoutePlanNode(Double.parseDouble(MyApplication.getInstance().getLongitude()), Double.parseDouble(MyApplication.getInstance().getLatitude()), "我的位置", null, coType);
                eNode = new BNRoutePlanNode(mStoreDetail.getData().getLongitude(), mStoreDetail.getData().getLatitude(), mStoreDetail.getData().getName(), null, coType);
                break;
            }
        }
        if (sNode != null && eNode != null) {
            List<BNRoutePlanNode> list = new ArrayList<BNRoutePlanNode>();
            list.add(sNode);
            list.add(eNode);
            BaiduNaviManager.getInstance().launchNavigator(getActivity(), list, 1, true, new DemoRoutePlanListener(sNode));
        }
    }

    public class DemoRoutePlanListener implements BaiduNaviManager.RoutePlanListener {

        private BNRoutePlanNode mBNRoutePlanNode = null;

        public DemoRoutePlanListener(BNRoutePlanNode node) {
            mBNRoutePlanNode = node;
        }

        @Override
        public void onJumpToNavigator() {
            if (dialog != null && dialog.isShowing()) {
                dialog.dismiss();
            }
            /*
             * 设置途径点以及resetEndNode会回调该接口
			 */

            for (Activity ac : OffLineShopDetailActivtiy.activityList) {

                if (ac.getClass().getName().endsWith("MapNaviActivity")) {
                    return;
                }
            }
            Intent intent = new Intent(UiUtils.getContext(), MapNaviActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable(OffLineShopDetailActivtiy.ROUTE_PLAN_NODE, mBNRoutePlanNode);
            intent.putExtras(bundle);
            intent.putExtra("type", "5");
            startActivity(intent);

        }

        @Override
        public void onRoutePlanFailed() {
            if (dialog != null && dialog.isShowing()) {
                dialog.dismiss();
            }
            ToastUtil.show("导航失败");
        }
    }

    /**
     * 弹出分享界面
     */
    private void initPopuWindow() {
        View popupWindow_view = getActivity().getLayoutInflater().inflate(R.layout.pop_shared, null, false);
        popupWindow = new PopupWindow(popupWindow_view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0xb0000000));
        popupWindow.setFocusable(true);
        popupWindow.showAtLocation(mLlShare, Gravity.BOTTOM, 0, 0);
        TextView tv_cancle = (TextView) popupWindow_view.findViewById(R.id.tv_cancle);
        LinearLayout ll_qq = (LinearLayout) popupWindow_view.findViewById(R.id.ll_qq);
        LinearLayout ll_wechat = (LinearLayout) popupWindow_view.findViewById(R.id.ll_wechat);
        LinearLayout ll_qzone = (LinearLayout) popupWindow_view.findViewById(R.id.ll_qzone);
        LinearLayout ll_friendscircle = (LinearLayout) popupWindow_view.findViewById(R.id.ll_friendscircle);
        View.OnClickListener shareClickListener = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.ll_qq:
                        platform = SHARE_MEDIA.QQ;
                        break;
                    case R.id.ll_wechat:
                        platform = SHARE_MEDIA.WEIXIN;
                        break;
                    case R.id.ll_qzone:
                        platform = SHARE_MEDIA.QZONE;
                        break;
                    case R.id.ll_friendscircle:
                        platform = SHARE_MEDIA.WEIXIN_CIRCLE;
                        break;
                }
                UMWeb mUMWeb = new UMWeb(Url.IMG_URL + "/Home/pars/offline_get_url?id=" + mStoreDetail.getData().getId());
                mUMWeb.setTitle("正常消费，额外再获一倍奖励=免费消费");
                mUMWeb.setDescription("推荐一个商家;正常消费,额外获豆豆,红豆可提现！");
                mUMWeb.setThumb(new UMImage(getActivity(), R.mipmap.logo));
                new ShareAction(getActivity()).setPlatform(platform)
                        .setCallback(umShareListener)
                        .withMedia(mUMWeb)
                        .share();
                popupWindow.dismiss();
            }
        };
        ll_qq.setOnClickListener(shareClickListener);
        ll_wechat.setOnClickListener(shareClickListener);
        ll_qzone.setOnClickListener(shareClickListener);
        ll_friendscircle.setOnClickListener(shareClickListener);
        tv_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
    }

    private UMShareListener umShareListener = new UMShareListener() {

        @Override
        public void onStart(SHARE_MEDIA share_media) {
            // 分享开始
        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            if (platform.name().equals("WEIXIN_FAVORITE")) {
                ToastUtil.show(getString(R.string.collectSuccess));
            } else {
                ToastUtil.show(getString(R.string.shareSuccess));
            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            ToastUtil.show(getString(R.string.shareFaile));
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            ToastUtil.show(getString(R.string.shareCancel));
        }
    };

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onScroll(int scrollY) {
        if (scrollY >= mMeasuredHeight) {
            if (lienarScrollbody.getParent() != linearstop) {
                lineargegin.removeView(lienarScrollbody);
                lineargegin.setLayoutParams(new LinearLayout.LayoutParams(lienarScrollbody.getMeasuredWidth(), lienarScrollbody.getMeasuredHeight()));
                tvShopinfo.setVisibility(View.VISIBLE);
                linearstop.addView(lienarScrollbody);
            }
        } else {
            if (lienarScrollbody.getParent() != lineargegin) {
                linearstop.removeView(lienarScrollbody);
                tvShopinfo.setVisibility(View.GONE);
                lineargegin.addView(lienarScrollbody);
            }
        }
    }

    Handler mHandler = new Handler();

    @Override
    public void scrollBottom() {
        if (mIsMoreLoad && CommonTool.isFirstScroll()) {
            mAdapter.setLoadingState(mAdapter.LOADING);
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            page++;
                            initNet();
                        }
                    });
                }
            }, 1000);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(getActivity()).onActivityResult(requestCode, resultCode, data);
    }
}
